<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>个人简介</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .profile-image {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 3px solid #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .image-upload {
            position: relative;
            display: inline-block;
        }
        .image-upload input[type="file"] {
            display: none;
        }
        .image-upload label {
            cursor: pointer;
            position: absolute;
            bottom: 0;
            right: 0;
            background: #fff;
            padding: 5px 10px;
            border-radius: 20px;
            box-shadow: 0 0 5px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">个人简介</h2>
    </div>

    <div class="card">
        <div class="card-body">
            <form id="profileForm">
                <div class="text-center mb-4">
                    <div class="image-upload">
                        <img src="https://picsum.photos/id/1005/150/150" alt="个人头像" class="profile-image" id="profileImage">
                        <label for="imageInput">
                            <i class="fa fa-camera"></i>
                        </label>
                        <input type="file" id="imageInput" accept="image/*">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="nickName" class="form-label">昵称</label>
                        <input type="text" class="form-control" id="nickName" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="email" class="form-label">电子邮箱</label>
                        <input type="email" class="form-control" id="email" required>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">性别</label>
                    <div class="d-flex gap-3">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="gender" id="male" value="男">
                            <label class="form-check-label" for="male">男</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="gender" id="female" value="女">
                            <label class="form-check-label" for="female">女</label>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label for="bio" class="form-label">个人简介</label>
                    <textarea class="form-control" id="bio" rows="4" maxlength="500"></textarea>
                    <div class="form-text text-end">
                        <span id="charCount">0</span>/500
                    </div>
                </div>

                <button type="submit" class="btn btn-primary">保存修改</button>
            </form>
        </div>
    </div>
</div>

<script src="/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        // 获取当前用户ID
        const userId = sessionStorage.getItem('userId'); // 从sessionStorage获取用户ID

        if (!userId) {
            alert('用户未登录或登录信息已过期，请重新登录。');
            window.location.href = 'login.html'; // 跳转到登录页面
            return;
        }

        // 加载个人资料
        function loadProfile() {
            $.ajax({
                url: `http://localhost:8082/api/user/profile/${userId}`,
                method: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        const data = response.data;
                        console.log(data);
                        
                        // 设置表单值，如果值为null则设置为空字符串
                        $('#nickName').val(data.nickName || '');
                        $('#email').val(data.email || '');
                        // 处理性别选择
                        if (data.gender) {
                            console.log('Gender value:', data.gender);
                            $(`input[name="gender"][value="${data.gender}"]`).prop('checked', true);
                        }
                        $('#bio').val(data.bio || '');
                        if (data.avatarUrl) {
                            $('#profileImage').attr('src', 'http://localhost:8082/upload/' + data.avatarUrl);
                        } else {
                            // 如果没有头像，使用默认头像
                            $('#profileImage').attr('src', 'https://picsum.photos/id/1005/150/150');
                        }
                        updateCharCount();
                    }
                },
                error: function(xhr, status, error) {
                    alert('获取个人资料失败：' + error);
                }
            });
        }

        // 更新字数统计
        function updateCharCount() {
            const count = $('#bio').val().length;
            $('#charCount').text(count);
        }

        // 监听简介输入
        $('#bio').on('input', updateCharCount);

        // 处理头像上传
        $('#imageInput').on('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 创建 FormData 对象
                const formData = new FormData();
                formData.append('file', file);

                // 上传文件
                $.ajax({
                    url: 'http://localhost:8082/api/upload/img',
                    method: 'POST',
                    data: formData,
                    processData: false,  // 不处理数据
                    contentType: false,  // 不设置内容类型
                    success: function(response) {
                        if (response.code === 200) {
                            // 上传成功，更新头像显示
                            const avatarUrl = 'http://localhost:8082/upload/' + response.data;
                            $('#profileImage').attr('src', avatarUrl);
                            // 保存头像文件名到表单数据中
                            $('#profileForm').data('avatarUrl', response.data);
                            // 更新sessionStorage中的头像文件名
                            sessionStorage.setItem('avatarUrl', response.data);
                            alert('头像上传成功！');
                        } else {
                            alert('头像上传失败：' + response.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('头像上传失败：' + error);
                    }
                });
            }
        });

        // 处理表单提交
        $('#profileForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = {
                userId: userId,
                nickName: $('#nickName').val(),
                email: $('#email').val(),
                gender: $('input[name="gender"]:checked').val(),
                bio: $('#bio').val(),
                avatarUrl: $('#profileForm').data('avatarUrl') || null
            };

            $.ajax({
                url: 'http://localhost:8082/api/user/profile/',
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.code === 200) {
                        alert('个人资料更新成功');
                    } else {
                        alert('更新失败：' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    alert('更新失败：' + error);
                }
            });
        });

        // 初始加载个人资料
        loadProfile();
    });
</script>
</body>
</html> 